package cc.zoyn.momentimageclubclient.handler;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Process;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 崩溃处理器
 *
 * @author Zoyn
 * @since 2017-09-26
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashReport";
    private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/瞬间影像/CrashReport/";
    private static final String FILE_NAME = "crash-report-%s-client.txt";
    private static CrashHandler instance;
    private Context context;

    private CrashHandler() {
    }

    public static CrashHandler getInstance() {
        if (instance == null) {
            instance = new CrashHandler();
        }
        return instance;
    }

    public void initial(Context context) {
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.context = context;
    }

    /**
     * 处理程序中未被捕获的异常
     *
     * @param thread    线程
     * @param throwable 抛出的异常
     */
    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        try {
            saveCrashReport(throwable);
            // 两秒后退出应用
            Thread.sleep(2000);
            android.os.Process.killProcess(Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存崩溃信息
     *
     * @param throwable
     */
    public void saveCrashReport(Throwable throwable) {
        File path = new File(PATH);
        if (!path.exists()) {
            path.mkdirs();
        }

        String time = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss").format(new Date());
        String fileName = String.format(FILE_NAME, time);
        File file = new File(PATH, fileName);

        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);

            file.createNewFile();
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
            writer.println("---- MIC Crash Report ----\n");
            writer.println("时间: " + time);
            writer.println("描述信息: " + throwable.getMessage());
            writer.println();
            writer.println("堆栈跟踪: ");
            throwable.printStackTrace(writer);
            writer.println();
            writer.println("---- 运行信息 ----");
            writer.println("客户端版本: " + packageInfo.versionName);
            writer.println("Android版本: " + Build.VERSION.RELEASE + "_" + Build.VERSION.SDK_INT);
            writer.println("手机型号: " + Build.MODEL);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            Log.e(TAG, "保存崩溃信息时发生错误!");
        }
    }
}
